42. Solution: Using a CursorLoader

Using a CursorLoader Solution

In this exercise you replaced the AsyncTaskLoader with a CursorLoader that gets data from the ContentProvider. Great job!!

Notes on Solution Code

One of the biggest changes to the Sunshine code was to update the ForecastAdapter and change its onBindViewHolder method so that it takes all of the data from a cursor and uses that to populate the views.

The final implementation of onBindViewHolder should look like this:

    @Override
    public void onBindViewHolder(ForecastAdapterViewHolder forecastAdapterViewHolder, int position) {

        // Move the cursor to the appropriate position
        mCursor.moveToPosition(position);

        // Generate a weather summary with the date, description, high and low
        /* Read date from the cursor */
        long dateInMillis = mCursor.getLong(MainActivity.INDEX_WEATHER_DATE);
        /* Get human readable string using our utility method */
        String dateString = SunshineDateUtils.getFriendlyDateString(mContext, dateInMillis, false);
        /* Use the weatherId to obtain the proper description */
        int weatherId = mCursor.getInt(MainActivity.INDEX_WEATHER_CONDITION_ID);
        String description = SunshineWeatherUtils.getStringForWeatherCondition(mContext, weatherId);
        /* Read high temperature from the cursor (in degrees celsius) */
        double highInCelsius = mCursor.getDouble(MainActivity.INDEX_WEATHER_MAX_TEMP);
        /* Read low temperature from the cursor (in degrees celsius) */
        double lowInCelsius = mCursor.getDouble(MainActivity.INDEX_WEATHER_MIN_TEMP);

        String highAndLowTemperature =
                SunshineWeatherUtils.formatHighLows(mContext, highInCelsius, lowInCelsius);

        String weatherSummary = dateString + " - " + description + " - " + highAndLowTemperature;

       // Display the summary that you created above
        forecastAdapterViewHolder.weatherSummary.setText(weatherSummary);
    }

To view all the changes to the ForecastAdapter and the MainActivity loader code, see the solution and comparison code linked below.

Solution Code

Solution: [S09.04-Solution-UsingCursorLoader][Diff]